package com.nf.db.handlers.map;

import com.nf.db.handlers.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.nf.db.handlers.RowProcessor.DEFAULT_ROWPROCESSOR;

/*
 * 让ResultSetHandler处理结果集，并将结果集转换为map<Object, T>
 * */
public abstract class AbstractMapHandler<T> implements ResultSetHandler<Map<Object, T>> {
    protected String columnName;
    protected int columnIndex;

    protected AbstractMapHandler() {
        this(null, 1);
    }

    protected AbstractMapHandler(String columnName) {
        this(columnName, -1);
    }

    protected AbstractMapHandler(int columnIndex) {
       this(null, columnIndex);
    }

    protected AbstractMapHandler(String columnName, int columnIndex) {
        this.columnName = columnName;
        this.columnIndex = columnIndex;
    }

    @Override
    public Map<Object, T> handle(ResultSet rs) throws SQLException {
        Map<Object, T> result = new HashMap<Object, T>();
        while (rs.next()) {
            Object key = getKey(rs, columnName, columnIndex);
            T value = getValue(rs);
            result.put(key, value);
        }
        return result;
    }

    protected Object getKey(ResultSet rs, String columnName, int columnIndex) throws SQLException {
        return DEFAULT_ROWPROCESSOR.toScalar(rs, columnName, columnIndex);
    }

    protected abstract T getValue(ResultSet rs) throws SQLException;
}
